package com.stony.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

/**
 * Created by ShiHui on 2014/6/18.
 */
public class OnlineUserListener implements HttpSessionListener {

    Logger log = LoggerFactory.getLogger(OnlineUserListener.class);

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();

        String username = (String) session.getAttribute("username");
        List onlineUserList = (List) application.getAttribute("onlineUserList");

        if (onlineUserList == null) {
            onlineUserList = new ArrayList();
            application.setAttribute("onlineUserList", onlineUserList);
        }
        onlineUserList.add(username);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();


        String username = (String) session.getAttribute("username");


        List onlineUserList = (List) application.getAttribute("onlineUserList");
        onlineUserList.remove(username);

        log.info(username + "超时退出!");
    }

}
